import Vue from 'vue'
import Vuex from 'vuex'
import productList from '../product'

Vue.use(Vuex)

// 数组排重
function getFilterArray (array) {
    const res = [];
    const json = {};
    for (var i = 0; i < array.length; i++) {
      const _self = array[i];
      if(!json[_self]){
        res.push(_self);
        json[_self] = 1;
      }
    }

    return res;
}

export default new Vuex.Store({
  state : {
      productList:[],
      cartList:[]
  },
  getters : {
    // 获取品牌列表
    brands: state => {
        const brands = state.productList.map(item => item.brand);
        return getFilterArray(brands);
    },
    // 获取颜色列表
    colors: state => {
      const colors = state.productList.map(item => item.color);
      return getFilterArray(colors);
    }
  },
  mutations : {
    // 商品列表
    setProductList (state, data) {
      state.productList = data;
    },
    // 添加购物车
    addCart (state, id){
      const isAdded = state.cartList.find(item => item.id == id);
      if (isAdded) {
        isAdded.count++
      }else{
        state.cartList.push({
          id:id,
          count:1
        })
      }
    },
    editCartCount (state, obj) {
      const product = state.cartList.find(item => item.id == obj.id);
      product.count += obj.count;
    },
    deleteCart (state, id){
      const index = state.cartList.findIndex(item => item.id == id);
      state.cartList.splice(index,1);
    },
    emptyCart (state) {
      state.cartList = [];
    }

  },
  actions : {
    // 请求商品列表
    getProductList (context) {

      setTimeout(() => {
        context.commit("setProductList",productList);
        console.info(productList);
      },500)
    },
    buy (context) {
      // 真实环境应通过 ajax 提交购买请求后再清空购物列表
            return new Promise(resolve=> {
                setTimeout(() => {
                    context.commit('emptyCart');
                    resolve();
                }, 500)
            });
    }
  }
})
